package com.libgdxbar.pvzlikegame.systems.animation;

import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.ObjectMap;
import org.libgdxbar.projects.interfaces.animation.BaseTrackEntry;
import org.libgdxbar.projects.interfaces.animation.GdxAnimation;

public class Animator {

    private static final TrackEntry defaultTrackEntry = new TrackEntry();

    private float stateTime;
    private float lastStateTime;
    private TrackEntry trackEntry = defaultTrackEntry;
    private ObjectMap<String, TrackEntry> namedAnimations = new ObjectMap<>();

    public TrackEntry addAnimator(GdxAnimationImpl gdxAnimationImpl) {
        if (gdxAnimationImpl == null) {
            throw new RuntimeException("动画缺失");
        }
        TrackEntry trackEntry = new TrackEntry();
        trackEntry.setAnimation(gdxAnimationImpl);
        namedAnimations.put(gdxAnimationImpl.getName(), trackEntry);
        return trackEntry;
    }

    public TrackEntry setAnimation(String name) {
        TrackEntry trackEntry = namedAnimations.get(name, defaultTrackEntry);
        if (trackEntry == defaultTrackEntry) {
            System.out.println("动画切换失败，撤销");
            return trackEntry;
        }
        return new TrackEntry(trackEntry);
    }

    public void update(float dt) {
        lastStateTime = stateTime;
        stateTime += dt;
        this.updateAnimationListener();
    }

    // TODO 事件未处理完成
    private void updateAnimationListener() {
        if (lastStateTime == 0f) {
            if (trackEntry.getListener() != null) {
                trackEntry.getListener().onAnimationStart(trackEntry);
            }
        }
        float duration = trackEntry.getAnimation().getDuration();
        if (stateTime >= duration) {
            if (trackEntry.getListener() != null) {
                trackEntry.getListener().onAnimationEnd(trackEntry);
            }
        }
    }

	public GdxAnimation getAnimation(){
		return trackEntry.getAnimation();
	}

	public TextureRegion getFrame() {
		return trackEntry.getAnimation().getFrame(stateTime);
	}

	public static class TrackEntry extends BaseTrackEntry {

        public TrackEntry() {
        }

        public TrackEntry(TrackEntry other) {
            super(other);
        }
    }

}
